import { isEmpty, isNullOrUnDef } from "@/utils"
import { FormProps } from "../types"

/**
 * 表单数据
 *
 * 支持
 *  - 获取表单数据
 *  - 设置表单数据
 *  - 设置表单默认数据
 */
export function useFormData(props: Ref<FormProps>) {
    // 表单列定义
    const dataSchema = computed(() => {
        const { items = [] } = unref(props)
        return items.map(item => {
            const { property, defaultValue, type } = item
            return { property, defaultValue, type }
        })
    })
    // 加载状态
    const status = ref<boolean>(false)
    // 数据
    const dataRef = reactive<Recordable>({})
    // 默认数据
    const { cloned, sync } = useCloned(dataRef, { manual: true })

    /**
     * 设置数据
     */
    const setFormData = (data: Recordable) => {
        Object.keys(dataRef).forEach(k => (dataRef[k] = null))
        Object.keys(data).forEach(k => (dataRef[k] = data[k]))
    }

    /**
     * 设置数据
     */
    const setDefaultFormData = (data: Recordable) => {
        setFormData(data)
        sync()
    }

    /**
     * 获取数据
     */
    const getFormData = () => {
        return dataRef
    }

    /**
     * 重置表单数据
     */
    const resetForm = () => {
        setDefaultFormData(cloned.value)
    }

    /**
     * 初始化
     */
    function initFormData() {
        const { items = [] } = unref(props)
        items.forEach(item => {
            const { defaultValue } = item
            if (!isNullOrUnDef(defaultValue)) {
                dataRef[item.property] = defaultValue
            }
        })
        sync()
    }

    watch(
        () => dataSchema.value,
        schema => {
            if (status.value) {
                return
            }
            if (isEmpty(schema)) {
                return
            }
            initFormData()
            status.value = true
        }
    )

    return { data: dataRef, initFormData, setFormData, getFormData, setDefaultFormData, resetForm }
}
